package com.topisv.tms.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import net.sf.json.JSONObject;

import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;

/**
 * 
 * http访问请求工具类
 * 
 * @date 2016-1-15
 * @author chenhongtao
 *
 */
public class HttpClientUtil {

	/**
	 * 发送post请求方法
	 * 
	 * @param url
	 * @param paraMap
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked", "resource", "deprecation" })
	public static String doPost(String url, String charset,
			HashMap<String, String> paramMap) {

		HttpClient httpClient = null;
		HttpPost httpPost = null;
		String result = null;
		try {
			httpClient = new DefaultHttpClient();
			httpPost = new HttpPost(url);
			// 设置参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			Iterator iterator = paramMap.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, String> elem = (Entry<String, String>) iterator.next();
				nvps.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
			}
			if (nvps.size() > 0) {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps,charset);
				httpPost.setEntity(entity);
			}
			HttpResponse response = httpClient.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, charset);
					JSONObject jsons = JSONObject.fromObject(result);
					result= jsons.getString("data");
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			httpPost.releaseConnection();
		}
		
		return result;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String url = "http://api.ttk.cn/serverProxy/ProxyActionEx.php?";
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("arg1", "手机接口");
		paramMap.put("arg2", "通用_取大头笔");
//		paramMap.put("arg3", "{\"site"+":"+"总部","cus"+":"+"测试客户","password"+":"+"1234","getcount"+":"+"15"+"}");
	}

}
